package cn.mhome.easy.spring.thrift.client.support;

import java.util.HashMap;
import java.util.Map;

import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.mhome.spring.thrift.server.ConfigCenter;

public class ConnectManager {
	protected static Logger logger = LoggerFactory.getLogger(ConnectManager.class);
	public static final String SERVER_IP = "localhost";
	public static final int SERVER_PORT = 8101;
	public static final int TIMEOUT = 30000;

	/**
	 * 获取socket
	 * @param ip
	 * @param port
	 * @param timeout
	 * @return
	 * @throws TTransportException
	 */
	public static TTransport getConnect(String ip,int port,int timeout) throws TTransportException{
		if(ip == null){
			ip = SERVER_IP;
		}
		if(port <= 0) {
			port = SERVER_PORT;
		}
		if(timeout <= 0){
			timeout = TIMEOUT;
		}
		
		TFramedTransport transport = new TFramedTransport(new TSocket(ip, port,timeout));

		transport.open();
		
		return transport;
	}
	
	/**
	 * 关闭服务连接
	 * @param transport
	 */
	public static void close(TTransport transport){
		if(transport != null && transport.isOpen()){
			transport.close();
		}
	}
	
	private static Map<String,Object[]> addressMap = new HashMap<String,Object[] >();
	public synchronized static Object[] getAddressMap(String serviceName){
		 propertiesReloadInterceptor();
		 if(!addressMap.containsKey(serviceName)){
			 synchronized (addressMap) {
				 if(!addressMap.containsKey(serviceName)){
					 String[] svrNames = serviceName.split("\\.");
						String serverIp = ConfigCenter.getServerIp(svrNames[svrNames.length - 1]);
						int serverPort = ConfigCenter.getServerPort(svrNames[svrNames.length - 1]);
						
						//没有相应服务接口配置,获取服务地址ip
						if(serverIp == null || serverPort <= 0){
							String serverName = serviceName.split("\\.")[4];
							if(ConfigCenter.getServerInfo().containsKey(serverName)){
								serverIp = ConfigCenter.getServerInfo().getProperty(serverName).split("[:]")[0];
								serverPort = Integer.valueOf(ConfigCenter.getServerInfo().getProperty(serverName).split("[:]")[1]);
							}
						}
//						logger.info("serviceName:"+serviceName+",serverIp:"+serverIp+",serverPort:"+serverPort);
						Object[] address = new Object[]{serverIp,serverPort};
						addressMap.put(serviceName, address);
				 }
			}
			
		 }
		 return addressMap.get(serviceName);
	}
	
	public static void propertiesReloadInterceptor(){
		synchronized (addressMap) {
			addressMap.clear();
			ConfigCenter.readFromPropertiesFile();
		}
		
	}
}
